package jiaMian;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.border.LineBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import DDL.DataBase;
import DDL.DeleteTable;
import DDL.GetDataBaseList;
import DML.util;
import DuiXiang.TableModel;
import Main.ParsingSql;

import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.TableView.TableCell;

public class Testmain extends JFrame {
	JScrollPane scrollPane = new JScrollPane();
	static JScrollPane scrollPane_1;  //创建一个带有滚动条的Pane
	private JScrollPane scrollPane_2 = new JScrollPane();
	private JComboBox comboBox = new JComboBox(); //创建多选下拉框
	private JPopupMenu popMenu;
	private JTextField textField;       //定义文本框
	private JTable table;               //定义表格
	private DefaultTableModel tableModel;  //定义Table模型
	private static JTree tree = new JTree(); //创建一个树形结构tree
	List<JTree> treeList = new ArrayList<JTree>();   //将多个Tree型结构用List表示出来

	private String[] dbList;
	private String tableName;
	private String databaseName;
	private static List<String> lists = new ArrayList<String>();
	private String key;

	public Testmain() {
		setTitle("DBMS");
		setSize(645, 560);
		setLocationRelativeTo(null);

		setSize(new Dimension(581, 515));
		setVisible(true);
		addEvent(this);                      //增加事件函数
		getContentPane().setLayout(null);
		scrollPane_2.setBounds(135, 176, 398, 214);
		scrollPane_2.setViewportBorder(new LineBorder(new Color(0, 0, 0), 1,
				true));
		getContentPane().add(scrollPane_2);

		JMenuBar menuBar = new JMenuBar();    //新建菜单
		setJMenuBar(menuBar);

		JMenu menu = new JMenu("新建");        //新建目录
		menuBar.add(menu);

		JMenuItem menuItem = new JMenuItem("表");  //建立子目录
		menuItem.addActionListener(new CreateTableMenuEvent());
		menu.add(menuItem);

		JMenuItem menuItem_1 = new JMenuItem("数据库");
		menuItem_1.addActionListener(new CreateDatabaseMenuEvent());
		menu.add(menuItem_1);

		JMenu menu_2 = new JMenu("帮助");
		menu_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				JOptionPane.showMessageDialog(null, "测试SQL语句："+'\n'
				        +"新建数据库 CREATE  database Ceshi  "+'\n'
						+ "删除数据库 drop   database Ceshi "+'\n'
						+ "新建表    CREATE  TableCell ceshitable1 (Name  varchar[10] KEY  NO_NULL , Age int NOT_KEY NO_NULL VALID)INTO Ceshi"+'\n'
						+ "修改表项信息 EDIT TableCell ceshitable2(Name  char[10] KEY  NO_NULL , Age float NOT_KEY NO_NULL VALID)IN Ceshi"+'\n'
						+ "表中插入数据  insert into ceshitable values ('胡伟强',123) in Ceshi"+'\n'
						+ "更改表中数据  update ceshitable3(SET Age=22 where Name='胡伟强') in Ceshi"+'\n'
						+ "条件查询 select * from ceshitable in Ceshi"+'\n'
						+ "select Age from ceshitable where Name='胡伟强' in Ceshi"+'\n'
						+ "删除数据  delete from ceshitable where Name='胡伟强' in Ceshi;", "标题",  JOptionPane.WARNING_MESSAGE);
			}
		});
		
				
			
		
		menuBar.add(menu_2);

		JMenu menu_1 = new JMenu("关于");
		menu_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				JOptionPane.showMessageDialog(null, "本系统应用软件课程设计要求基于Java程序设计语言，"+'\n'
						+ "结合数据库技术、编译技术和文字处理技术设计一个DBMS系统，"+'\n'
						+ "帮助学生巩固数据结构、算法、程序设计的基础知识。"+'\n'
						+ "加强对数据库管理系统的内部机制的理解，学习DBMS的实现技术。", "标题",  JOptionPane.WARNING_MESSAGE);
			}
		});
		menuBar.add(menu_1);
		scrollPane.setBounds(135, 30, 398, 122);
		getContentPane().add(scrollPane);

		final JTextArea textArea = new JTextArea();
		scrollPane.setViewportView(textArea);
		textArea.setForeground(SystemColor.textText);
		textArea.setWrapStyleWord(true);
		textArea.setFont(new Font("Monospaced", Font.PLAIN, 13));
		textArea.setBackground(SystemColor.text);
		textArea.setLineWrap(true);

		JButton button = new JButton("执行");
		button.setBounds(272, -3, 93, 23);
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				String sql = textArea.getText();
				List<List<String>> resultSet = new ArrayList<List<String>>();
				ParsingSql p = new ParsingSql();
				textField.setText(p.parsingSql(sql, resultSet));
				showTable(resultSet);
//				getDblist(dbList);
//				comboBox.setModel(new DefaultComboBoxModel(dbList));
//				comboBox.validate();
                //validate();//重构面板内容
				comboBox.repaint();//重绘面板内容
			}
		});
		getContentPane().add(button);

		textField = new JTextField();
		textField.setBounds(375, -1, 167, 21);
		getContentPane().add(textField);
		textField.setColumns(10);

		scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(10, 10, 120, 423);
		scrollPane_1.setViewportBorder(new LineBorder(new Color(0, 0, 0), 1,
				true));
		getContentPane().add(scrollPane_1);

//		GetDataBaseList getData = new GetDataBaseList();
//		Map<String, List<String>> dirName = getData.getDataBaseList();
//
//		int dirNameLength = dirName.size();
//		String key = null;
//		String[] dbList = new String[dirNameLength];
//		int j = 0;
//		for (Map.Entry<String, List<String>> e : dirName.entrySet()) {
//			key = e.getKey();
//			dbList[j++] = key;
//		}
		

		GetDataBaseList getData = new GetDataBaseList();
		Map<String, List<String>> dirName = getData.getDataBaseList();

		int dirNameLength = dirName.size();
		String key = null;
		dbList= new String[dirNameLength];
		key=getDblist(dbList);
		showTree(scrollPane_1, key);
		//System.out.println(dbList);
		comboBox.setBounds(135, -1, 110, 21);
     
		comboBox.setModel(new DefaultComboBoxModel(dbList));
		comboBox.setEditable(true);

		comboBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent evt) {
				if (evt.getStateChange() == ItemEvent.SELECTED) {
					try {
						String s = evt.getItem().toString();// 选中的值
						Testmain.showTree(scrollPane_1, s);
					} catch (Exception e) {
					}
				}
			}
		});
		getContentPane().add(comboBox);

		
		
		JButton button_1 = new JButton("添加");
		button_1.setBounds(145, 400, 66, 23);
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String[] rowValues = { "" };
				tableModel.addRow(rowValues); // 添加一行
			}
		});
		getContentPane().add(button_1);

		JButton button_2 = new JButton("删除");
		button_2.setBounds(235, 400, 66, 23);
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectedRow = table.getSelectedRow();// 获得选中行的索引
				if (selectedRow != -1) // 存在选中行
				{
					tableModel.removeRow(selectedRow); // 删除行
				}
			}
		});
		getContentPane().add(button_2);
	}

	// 新建数据库
	class CreateDatabaseMenuEvent implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			databaseName = JOptionPane.showInputDialog(null, "databaseName:",
					"创建 ", 1);
			if (databaseName == null) {
				return;// 取消创建
			} else {
				ParsingSql parsingSql = new ParsingSql();
				parsingSql.parsingSql("CREATE  database " + databaseName + ";",
						null);
				comboBox.addItem(databaseName);
			}
		}
	}

	// 新建表
	class CreateTableMenuEvent implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			// 获取新建表的表名
			// http://blog.csdn.net/ethanq/article/details/7200658
			tableName = JOptionPane.showInputDialog(null, "TableName:", "创建 ",
					1);// ??????增加对输入为空的判断
			if (tableName == null) {
				return;// 取消创建
			}
			String[] columnNames = { "Field_Name", "Type", "KEY_Flag",
					"NULL_Flag", "VALID_Flag" }; // 列名
			String[][] tableVales = { { "", "", "", "", "" } }; // 数据
			tableModel = new DefaultTableModel(tableVales, columnNames);// 创建表
			table = new JTable(tableModel);
			table.setModel(tableModel);
			table.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
			// 将表格对象放到滚动面板对象上
			scrollPane_2.setViewportView(table);
			// 设定表格在面板上的大小
			table.setPreferredScrollableViewportSize(new Dimension(200, 70));
			// 超出大小后，JScrollPane自动出现滚动条
			scrollPane_2.setAutoscrolls(true);
			table.validate();

			final JButton btnApply1 = new JButton("Apply");
			final JButton btnRevert1 = new JButton("Revert");
			btnApply1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					String sqlSentence = "CREATE TABLE " + tableName + "(";

					for (int i = 0; i < table.getRowCount(); i++) {
						for (int j = 0; j < table.getColumnCount(); j++) {
							sqlSentence = sqlSentence + " "
									+ table.getValueAt(i, j).toString();
						}
						if (i < table.getRowCount() - 1)
							sqlSentence = sqlSentence + ",";
					}
					sqlSentence = sqlSentence + ")" + "INTO "
							+ comboBox.getSelectedItem().toString() + ";";
					System.out.println(sqlSentence);// 显示

					List<List<String>> resultSet = new ArrayList<List<String>>();
					ParsingSql p = new ParsingSql();
					textField.setText(p.parsingSql(sqlSentence, resultSet));
					
					getContentPane().remove(btnApply1);
					getContentPane().remove(btnRevert1);
					getContentPane().validate();
					getContentPane().repaint();
					showTable(resultSet);
				}
			});
			btnApply1.setBounds(385, 400, 66, 23);
			getContentPane().add(btnApply1);

			btnRevert1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// 清空修改
					table.validate();
				}
			});
			btnRevert1.setBounds(464, 400, 66, 23);
			getContentPane().add(btnRevert1);
		}
	}

	// 删除数据库
	class DeleteDatabaseMenuEvent implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			int conform = JOptionPane.showConfirmDialog(null, "是否确认删除？",
					"删除数据库确认", JOptionPane.YES_NO_OPTION);
			if (conform == JOptionPane.YES_OPTION) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();
				databaseName = node.toString();
				if (DataBase.dropDatabase(databaseName)) {
					textField.setText("删除成功！");
					comboBox.removeItem(databaseName);
				}
			}
		}
	}

	// 编辑表
	class EditTableMenuEvent implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
					.getLastSelectedPathComponent();
			if (node.getParent().getParent() == null) {
				databaseName = node.getParent().toString();
				tableName = node.toString();
				ParsingSql parsingSql = new ParsingSql();
				List<List<String>> resultSet = new ArrayList<List<String>>();
				System.out.println(parsingSql.parsingSql(" select * " + "from "
						+ tableName + " in " + databaseName + ";", resultSet));// select语句
				showTable(resultSet);
			}

			final JButton btnApply = new JButton("提交");
			final JButton btnRevert = new JButton("撤销");
			btnApply.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					String dbfPath = "D:\\database\\" + databaseName + "\\"
							+ tableName + ".dbf";
					List<TableModel> tableModelList = util
							.ReadTableModelList(dbfPath);
					System.out.println(tableModelList);// //

					ParsingSql p = new ParsingSql();
					// 先保存修改后的table，再清空！！！！！！！
					int r = table.getRowCount(), c = table.getColumnCount();
					Object[][] array = new Object[r][c];
					for (int i = 0; i < table.getRowCount(); i++) {
						for (int j = 0; j < table.getColumnCount(); j++) {
							array[i][j] = table.getValueAt(i, j);
						}
					}
					// 清空表
					p.parsingSql("delete from " + tableName + " in "
							+ databaseName + ";", null);
					// 插入表 insert into 表名 values ( , ) in 数据库名;

					for (int i = 0; i < r; i++) {
						String sqlSentence = "insert into " + tableName
								+ " values (";
						for (int j = 0; j < c; j++) {
							// 类型为字符串加单引号
							if (tableModelList.get(j).getsType().equals("char")
									|| tableModelList.get(j).getsType()
											.equals("varchar")) {
								sqlSentence = sqlSentence + "'"
										+ array[i][j].toString() + "'";
							} else {
								sqlSentence = sqlSentence
										+ array[i][j].toString();
							}
							if (j < c - 1)
								sqlSentence = sqlSentence + ",";
						}
						sqlSentence = sqlSentence + ")" + " in " + databaseName
								+ ";";
						System.out.println(sqlSentence);// //
						textField.setText(p.parsingSql(sqlSentence, null));
					}
					getContentPane().remove(btnApply);
					getContentPane().remove(btnRevert);
					getContentPane().validate();
					getContentPane().repaint();
				}
			});
			btnApply.setBounds(385, 400, 66, 23);
			getContentPane().add(btnApply);

			btnRevert.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// 清空修改
					JTree tree = (JTree) e.getSource();
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
							.getLastSelectedPathComponent();
					if (node.getParent().getParent() == null) {
						String databaseName = node.getParent().toString();
						String tableName = node.toString();
						ParsingSql parsingSql = new ParsingSql();
						List<List<String>> resultSet = new ArrayList<List<String>>();
						System.out.println(parsingSql.parsingSql(" select * "
								+ "from " + tableName + " in " + databaseName
								+ ";", resultSet));// select语句
						showTable(resultSet);
					}
				}
			});
			btnRevert.setBounds(464, 400, 66, 23);
			getContentPane().add(btnRevert);
		}
	}

	// 删除表
	class DeleteTableMenuEvent implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			int conform = JOptionPane.showConfirmDialog(null, "是否确认删除？",
					"删除表确认", JOptionPane.YES_NO_OPTION);
			if (conform == JOptionPane.YES_OPTION) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();
				databaseName = node.getParent().toString();
				tableName = node.toString();
				if (DeleteTable.deleteTable(databaseName, tableName)) {
					textField.setText("删除成功！");
				}
			}
		}
	}

	//点击显示表格
	private void addEvent(final Testmain value) {

		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				JTree tree = (JTree) e.getSource();
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();
				if (node.getParent().getParent() == null) {
					String databaseName = node.getParent().toString();
					String tableName = node.toString();
					ParsingSql parsingSql = new ParsingSql();
					List<List<String>> resultSet = new ArrayList<List<String>>();
					System.out.println(parsingSql.parsingSql(
							" select * " + "from " + tableName + " in "
									+ databaseName + ";", resultSet));// select语句
					value.showTable(resultSet);
				}
			}
		});

		tree.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int n = tree.getRowForLocation(e.getX(), e.getY());
				if (n < 0) {
					return;
				}
				if (e.getButton() == MouseEvent.BUTTON3) {
					// JTree tree = (JTree) e.getSource();
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
							.getLastSelectedPathComponent();
					if (node.getParent() == null) {
						// 根节点，弹出根节点菜单
						popMenu = new JPopupMenu();
						JMenuItem addItem = new JMenuItem("新建表");
						addItem.addActionListener(new CreateTableMenuEvent());
						JMenuItem delItem = new JMenuItem("删除数据库");
						delItem.addActionListener(new DeleteDatabaseMenuEvent());
						popMenu.add(addItem);
						popMenu.add(delItem);
						popMenu.show(e.getComponent(), e.getX(), e.getY());
					}
					if (node.getParent().getParent() == null) {
						// 如果为叶子，弹出叶子菜单
						popMenu = new JPopupMenu();
						JMenuItem editItem = new JMenuItem("编辑");
						editItem.addActionListener(new EditTableMenuEvent());
						JMenuItem delItem = new JMenuItem("删除表");
						delItem.addActionListener(new DeleteTableMenuEvent());
						popMenu.add(editItem);
						popMenu.add(delItem);
						popMenu.show(e.getComponent(), e.getX(), e.getY());

					}
				}
			}
		});
	}
    //显示表
	private void showTable(List<List<String>> resultSet) {
		if (resultSet != null) {// select执行结果

			String[] columnNames = new String[resultSet.get(0).size()]; // 列名
			for (int j = 0; j < resultSet.get(0).size(); j++) {
				columnNames[j] = resultSet.get(0).get(j);
			}
			String[][] tableVales = new String[resultSet.size() - 1][resultSet
					.get(0).size()]; // 数据
			for (int i = 1; i < resultSet.size(); i++) {
				for (int j = 0; j < resultSet.get(i).size(); j++) {
					tableVales[i - 1][j] = resultSet.get(i).get(j);
				}
			}

			tableModel = new DefaultTableModel(tableVales, columnNames);
			// 创建表
			table = new JTable(tableModel);
			table.setModel(tableModel);
			table.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
			// 将表格对象放到滚动面板对象上
			scrollPane_2.setViewportView(table);
			// 设定表格在面板上的大小
			table.setPreferredScrollableViewportSize(new Dimension(200, 70));
			// 超出大小后，JScrollPane自动出现滚动条
			scrollPane_2.setAutoscrolls(true);
			table.validate();
		}
	}

	//显示树形结构，数据库列表
	private static void showTree(JScrollPane scrollPane, String key) {
		final GetDataBaseList getData = new GetDataBaseList();
		Map<String, List<String>> dirName = getData.getDataBaseList();
		int i = 0;
		for (Map.Entry<String, List<String>> e : dirName.entrySet()) {
			final String db = e.getKey();
			i = i + 1;
			if (db.equals(key)) {
				lists = e.getValue();
				tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode(
						db) {
					{
						DefaultMutableTreeNode node_1;
						for (String list : lists) {
							node_1 = new DefaultMutableTreeNode(list);
							List<TableModel> tb = getData.getTableModel(db,
									list);
							for (TableModel t : tb) {
								node_1.add(new DefaultMutableTreeNode(t
										.getsFieldName()));
							}
							add(node_1);
						}
					}
				}));
				scrollPane.setViewportView(tree);
			}
		}
	}
	
	public static String getDblist(String[] dbList){
		GetDataBaseList getData = new GetDataBaseList();
		Map<String, List<String>> dirName = getData.getDataBaseList();

		String key = null;
		int j = 0;
		for (Map.Entry<String, List<String>> e : dirName.entrySet()) {
			key = e.getKey();
			dbList[j++] = key;
		}
		
		return key;
	}
}
